import { reqLogin, reqLogout, reqUserInfo } from "@/api/user";
import type { LoginRequestData } from "@/api/user/type";
import { constantRoute } from "@/router/routers";
import { getToken, removeToken, setToken } from "@/storage/token";
import { defineStore } from "pinia";
import type { RouteRecordRaw } from "vue-router";

export interface UserState {
    name: String | null,
    avatar: string | null,
    token: string | null,
    menuRoutes: RouteRecordRaw[]
}

const useUserStore = defineStore('User', {
    state: (): UserState => {
        return {
            name: null,
            avatar: null,
            token: getToken(),
            menuRoutes: constantRoute
        }
    },
    actions: {
        // 登录
        async login(data: LoginRequestData) {
            const result = (await reqLogin(data)).data
            if (result.ok) {
                this.token = result.data as string;
                setToken(this.token);
            } else {
                return Promise.reject(new Error("用户名或密码错误"))
            }
        },

        // 登出
        async logout() {
            try {
                await reqLogout();
            } finally {
                removeToken();
                this.$reset();
            }
        },

        // 用户信息
        async userInfo() {
            const response = (await reqUserInfo()).data;
            if (response.code === 200) {
                this.name = response.data.name;
                this.avatar = response.data.avatar;
            }
        }


    },
    getters: {

    }
})

export default useUserStore;